<template>
    <div class="y-chat-page page-item price-page">
        <div class="ask-wrapper">
            <div class="ask-cover" style="padding-top: .41rem;">
                <img v-if="!config.ASK_HOME_HEADER_TEXT" referrerpolicy="no-referrer" :src="config.ASK_HOME_COVER_URL"
                     alt="" class="mc-img">
                <div v-else v-html="config.ASK_HOME_HEADER_TEXT"></div>
            </div>
            <div class="ask-item"
                 v-for="(item , index) in getOptions"
                 :key="index">
                <div class="title">
                    {{ item.title }}
                </div>
                <Radio :item="item" v-model="item.value"></Radio>
            </div>
            <div class="ask-form-group" v-if="config.IN_CURRENT_PAGE">
                <div class="ask-form-tips">
                    <p>
                        <span class="q">*</span>{{ config.IN_CURRENT_TIP_TEXT }}
                    </p>
                </div>
                <form class="ask-form">
                    <div class="ask-form-item" :class="{error : !!error.name , 'hidden-name-input' : hiddenName}">
                        <div class="ask-form-input">
                            <div class="label-text">
                                姓名 (已加密): <span class="hidden-text">{{ hiddenName ? '匿名' :'' }}</span>
                                <label class="hidden-name">
                                    <input v-model="hiddenName" type="checkbox" style="display: inline-block;"> 匿名
                                </label>
                            </div>
                            <input v-if="!hiddenName" class="input-el" type="text" autocomplete="off" name="name"
                                   placeholder="请输入您的姓名"
                                   v-model="form.name"
                                   @blur="validatorName">
                        </div>
                        <div class="error-message">
                            {{ error.name }}
                        </div>
                    </div>
                    <div class="ask-form-item" :class="error.phone && 'error'">
                        <div class="ask-form-input">
                            <div class="label-text">
                                电话 (已加密):
                            </div>
                            <input class="input-el"
                                   type="text"
                                   autocomplete="off"
                                   name="phone"
                                   placeholder="请输入您的电话号码"
                                   v-model="form.phone"
                                   @blur="validatorPhone">
                        </div>
                        <div class="error-message">
                            {{ error.phone }}
                        </div>
                    </div>

                </form>
                <div class="ask-button ask-form-btn">
                    <button @click="currentPageSubmit">
                        {{ buttonText}}
                    </button>
                </div>
            </div>
            <div class="ask-button"
                 v-if="!config.IN_CURRENT_PAGE"
                 :class="!showAskButton && 'disabled'">
                <button @click="openComputedPriceModal">
                    {{ buttonText}}
                </button>
            </div>
            <div class="ask-recode" v-if="showRecode" v-html="recodeText">
            </div>
        </div>
        <transition name="fade">
            <div class="mask-container" v-if="showCommentForm"></div>
        </transition>
        <transition name="slide-up">
            <ComputePrice :show.sync="showCommentForm"
                          @submit="handleSubmit"
                          v-if="showCommentForm"></ComputePrice>
        </transition>
    </div>
</template>

<script>
    import { mapActions }               from 'vuex';
    import ComputePrice                 from '../components/Computed-Price';
    import { cloneOf, paramsToMessage } from "../utily/util";
    import Radio                        from '../components/radio'
    import Swal                         from 'sweetalert2';


    export default {
        components: {
            ComputePrice,
            Radio
        },
        data() {
            return {
                showCommentForm: false,
                renderQuestion : [],
                question       : cloneOf(CONFIG.PRICE_PAGE.QUESTION),
                config         : CONFIG.PRICE_PAGE,
                data           : {},
                buttonText     : CONFIG.PRICE_PAGE.ASK_BTN_TEXT || '计算项目费用',
                showRecode     : CONFIG.PRICE_PAGE.SHOW_RECODE,
                recodeText     : CONFIG.PRICE_PAGE.RECODE_TEXT,
                hiddenName     : false,
                error          : {
                    name : '',
                    phone: '',
                },
                form           : {
                    name : '',
                    phone: '',
                },

            }
        },
        mounted() {
            this.question = this.parseQuestion(this.question);
        },
        methods   : {
            ...mapActions({
                $modal          : 'Controller/$modal',
                sendText        : 'Bridge/sendText',
                postToServe     : 'Bridge/postToServe',
                checkIsSubmitted: 'Bridge/checkIsSubmitted',
                showPostLoading : 'Controller/showPostLoading',
            }),
            parseQuestion(data) {
                return data.map((item) => {
                    item.options = item.options.map((option) => {
                        if (typeof option === 'string') {
                            option = {
                                value: option,
                            }
                        }

                        if (option.children && option.children.length) {
                            option.children = this.parseQuestion(option.children);
                        }

                        return option;
                    });
                    return item;
                })
            },
            handleRadioChange(item) {
            },
            validatorPhone() {
                const val = this.form.phone;
                let msg   = '';

                if (!val) {
                    msg = '电话不能为空.';
                } else if (!(/^1[34578]\d{9}$/.test(val))) {
                    msg = '电话格式有误.';
                }
                this.error.phone = msg;
            },
            validatorName() {
                let msg = '';
                if (!this.hiddenName) {
                    const val = this.form.name;
                    if (!val) {
                        msg = '姓名不能为空.';
                    }
                }
                this.error.name = msg;
            },
            async currentPageSubmit() {
                if (await this.checkIsSubmitted()) {
                    this.validatorName();
                    this.validatorPhone();

                    if (!this.error.name && !this.error.phone) {
                        let form       = this.form;
                        let hiddenName = this.hiddenName;
                        let data       = {
                            name : hiddenName ? '匿名' : form.name,
                            phone: form.phone,
                        };

                        this.handleSubmit(data);
                    }
                }
            },
            async handleSubmit(form) {
                let arr = {};

                this.getOptions.forEach(function (item) {
                    arr[ item.title ] = item.value;
                });

                const send = () => {
                    let value = paramsToMessage({
                        ...arr,
                        ...form,
                    });
                    this.sendText({
                        value,
                        display : false,
                        aglPlus : true,
                        typeName: this.getQuestionLinkType,
                    });
                };

                let type = window.__chatType;
                switch (type) {
                    case "yiliao":
                        this.$bus.$emit('init-easy-live',
                            () => {
                                send();
                            });
                        break;
                    case "server":
                        this.showPostLoading();
                        await this.postToServe({
                            ...form,
                            question_data: arr
                        });
                        Swal.close();
                        break;
                    default:
                        send();
                        break;
                }

                this.showCommentForm = false;
                Swal.fire({
                    'title': '提交成功',
                    'text' : '我们稍后会将计算结果通知您!',
                    'icon': 'success',
                    'confirmButtonText': '确认',
                }).then((action) => {
                    if (action.isConfirmed && CONFIG.PRICE_PAGE.JUMP_TO_CHAT) {
                        this.$router.push({
                            path : '/chat',
                            query: {
                                posted: true,
                            }
                        })
                    }
                })
            },
            async openComputedPriceModal() {
                if (this.showAskButton && !this.showCommentForm) {
                    if (await this.checkIsSubmitted())
                        this.showCommentForm = true;
                } else {
                    this.$model({
                        content: '请选择',
                    });
                }
            },
            getQuestionTree(value, arr) {
                arr        = arr || [];
                const item = this.question[ value ];

                if (item) {
                    arr     = arr.concat(item);
                    let key = '';
                    item.forEach(function (each) {
                        key += each.value;
                    });
                    return this.getQuestionTree(key, arr);
                }

                return arr;
            },
            parseSelectQuestion(data, arr = []) {
                data.forEach((item) => {
                    arr.push(item);
                    if (item.value && item.options) {
                        let cache = item.options.find(e => e.value === item.value);
                        if (cache) {
                            cache.typeName && (item.typeName = cache.typeName);
                            cache.children && this.parseSelectQuestion(cache.children, arr);
                        }
                    }
                });
                return arr;
            }
        },
        computed  : {
            getQuestionLinkType() {
                let type = this.getOptions.findLast((item) => {
                    return !!item.typeName;
                });
                return (type && type.typeName) || CONFIG.BASE.TYPE;
            },
            showAskButton() {
                return this.selectOption;
            },
            getOptions() {
                return this.parseSelectQuestion(this.question);
            },
            selectOption() {
                return this.getOptions.findIndex(function (item) {
                    return !item.value;
                }) === -1;
            }
        }
    }
</script>

<style lang="less" scoped>
    .ask-form-tips {
        margin: .7rem 0;
        font-size: .35rem;
        line-height: 1.3;
        color: #6c757d;

        .q {
            font-size: .4rem;
            margin-right: .1rem;
        }
    }

    .ask-form-btn {
        padding-top: .2rem;
    }

    .ask-form {
        display: flex;
        flex-direction: column;

        .hidden-name {
            position: absolute;
            right: 0;
            top: 0;
            bottom: 0;
            color: #7584f1;
            font-weight: bold;
        }

        .ask-form-item {
            display: flex;
            flex-direction: column;

            &.hidden-name-input {
                .label-text {
                    margin-bottom: .3rem;
                }

                .error-message {
                    display: none !important;
                }
            }

            &.error {
                .input-el {
                    border-color: #dc3545 !important;
                }

                .error-message {
                    opacity: 1;
                }
            }

            .ask-form-input {
                display: flex;
                flex-direction: column;
                font-size: .4rem;
                margin-top: .2rem;

                .label-text {
                    color: #353535;

                    .hidden-text {
                        margin-left: .2rem;
                        font-weight: bold;
                        color: #7d8bf2;
                    }
                }

                .input-el {
                    margin-top: .3rem;
                    height: .9rem;
                    line-height: .9rem;
                    padding: 0 .3rem;
                    border: 1px solid #e5e6fc;
                    border-radius: 0.1rem;
                    background-color: #fdfdff;
                    color: #495057;
                    transition: border .3s ease-in-out;
                }
            }

            .error-message {
                margin-top: .1rem;
                margin-bottom: .2rem;
                font-size: .32rem;
                transition: opacity .2s ease-in-out;
                opacity: 0;
                color: #de4353;
            }


        }

    }

    .ask-form-title {
        text-align: center;
        font-size: .5rem;
        color: #555;
        padding: .48rem 0;
    }

    .ask-form-item {
        input {

        }
    }

</style>

